package Socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
    聊天室服务端
 */
public class Server2 {
    private ServerSocket serverSocket;

    public Server2() {
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            System.out.println("成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void Start() {
        try {
            while(true) {
                System.out.println("等待客户连接中...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接成功");
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                System.out.println("说话：");
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }
        } catch(IOException e){
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        Server2 server = new Server2();
        server.Start();
    }

    private class clientHandler implements Runnable{
        private Socket socket;
        public clientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try
            {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                /*
                    如果客户端异常断开，服务端会抛出异常
                    java.net.SocketException: Connection reset
                    该异常无法避免，因为这个是客户端的操作导致的。
                 */
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println("客户端说:" + line);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
